package com.mishow.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.AMap.OnMarkerClickListener;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.android.volley.Request;
import com.bumptech.glide.request.animation.DrawableCrossFadeFactory;
import com.mishow.R;
import com.mishow.activity.ChatMishowActivity;
import com.mishow.bean.UserDistanceVO;
import com.mishow.fragment.base.BaseFragment;
import com.mishow.log.MyLog;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.UserDistanceResponse;
import com.mishow.request.response.UserDistanceResponse.Result;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.utils.ImageLoader.ImageLoaderProxy;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.widget.EmptyDataLayout;
import com.mishow.widget.RoundCornerImageView;

/**
 * 
 * 作者：wei.miao <br/>
 * 描述：搜附近-地图显示
 */
public class SearchNearMapFragment extends BaseFragment {

	private Activity mActivity;
	/** 数据为空 **/
	private EmptyDataLayout ll_search_reds_empty;

	private MapView map_view;

	/**
	 * 定义AMap 地图对象的操作方法与接口
	 **/
	private AMap aMap;
	/**
	 * 设置用户界面的一个AMap。调用AMap 的getUiSettings() 方法可以获得类的实例
	 **/
	private UiSettings mUiSettings;
	/**
	 * 定义了一个marker 的选项
	 **/
	private MarkerOptions markerOption;
	/**
	 * Marker 是在地图上的一个点绘制图标
	 **/
	private Marker marker2;// 有跳动效果的marker对象
	private LatLng latlng;
	/**
	 * 关键字
	 **/
	private String mKeyword;
	/**
	 * 纬度
	 **/
	private double latitude;
	/**
	 * 经度
	 **/
	private double longitude;
	
	private SharedPreferencesUtil mShPreferencesUtil;
	
	private Bundle savedInstanceState;

	public static SearchNearMapFragment newInstance() {

		SearchNearMapFragment fragment = new SearchNearMapFragment();
		return fragment;
	}

	public static SearchNearMapFragment newInstance(int status) {

		Bundle args = new Bundle();
		args.putInt("", status);
		SearchNearMapFragment fragment = new SearchNearMapFragment();
		fragment.setArguments(args);
		return fragment;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onAttach(Activity activity) {

		this.mActivity = activity;
		super.onAttach(activity);

	}
	
	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.savedInstanceState = savedInstanceState;
		mShPreferencesUtil = new SharedPreferencesUtil(mActivity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		View mView = inflater.inflate(R.layout.fragment_search_nearby_map,container, false);
		initData();
		setAttribute();
		initView(mView, savedInstanceState);

		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	private void initData() {

		/*latitude = Double.parseDouble(mShPreferencesUtil.getLatitude().trim());
		longitude = Double.parseDouble(mShPreferencesUtil.getLongitude().trim());
		latlng = new LatLng(latitude, longitude);*/
		try {
			latitude = Double.parseDouble(mShPreferencesUtil.getLatitude().trim());
			longitude = Double.parseDouble(mShPreferencesUtil.getLongitude().trim());
			latlng = new LatLng(latitude, longitude);
		} catch (Exception e) {
			//e.printStackTrace();
			MyLog.d(e.getMessage());
		}
		
	}

	/**
	 * 初始化view
	 * 
	 * @param view
	 */
	private void initView(View view, Bundle savedInstanceState) {

		ll_search_reds_empty = (EmptyDataLayout) view.findViewById(R.id.ll_search_reds_empty);

		map_view = (MapView) view.findViewById(R.id.map_view);

		// 在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，实现地图生命周期管理
		map_view.onCreate(this.savedInstanceState);// 此方法必须重写
		initMapView();
	}

	private void setAttribute() {

		getDistanceUserFromApi();
	}

	private void initMapView() {

		if (aMap == null) {
			aMap = map_view.getMap();
			mUiSettings = aMap.getUiSettings();
		}
		setUpMap();
		// 设置地图是否可以手势缩放大小
		mUiSettings.setZoomGesturesEnabled(true);
		// 设置地图默认的缩放按钮是否显示
		mUiSettings.setZoomControlsEnabled(false);
		// 设置地图是否可以手势滑动
		mUiSettings.setScrollGesturesEnabled(true);

		// 设置地图默认的定位按钮是否显示
		// mUiSettings.setMyLocationButtonEnabled(false);
		// 是否可触发定位并显示定位层
		// aMap.setMyLocationEnabled(false);

	}

	private void setUpMap() {
		// aMap.setOnMarkerDragListener(this);// 设置marker可拖拽事件监听器
		aMap.setOnMapLoadedListener(onMapLoadedListener);// 设置amap加载成功事件监听器
		aMap.setOnMarkerClickListener(onMarkerClickListener);//
		// 设置点击marker事件监听器
		//aMap.setOnInfoWindowClickListener(onInfoWindowClickListener);//
		// 设置点击infoWindow事件监听器
		aMap.setInfoWindowAdapter(infoWindowAdapter);// 设置自定义InfoWindow样式
	}

	/**
	 * 在地图上添加marker
	 */
	private void addMarkersToMap(ArrayList<UserDistanceVO> result) {
		// 系统默认marker背景图片
		// BitmapDescriptorFactory.HUE_AZURE
		// 动画效果
		// ArrayList<BitmapDescriptor> giflist = new
		// ArrayList<BitmapDescriptor>();
		// giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
		// giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
		// giflist.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
		markerOption = new MarkerOptions();
		// 定义marker 图标的锚点
		markerOption.anchor(0.5f, 0.5f);
		// 设置当前MarkerOptions 对象的经纬度
		markerOption.position(latlng);
		// 设置 Marker 的标题
		//markerOption.title("北京市");
		// 多图片刷新模拟gif动画 icons 设置会使用 icon方法覆盖
		// markerOption.icons(giflist);

		markerOption.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_clinic_loaction_pin));
		// 设置标记是否可拖动
		markerOption.draggable(true);
		// 设置多少帧刷新一次图片资源
		markerOption.period(10);

		if (result != null && result.size() > 1 ) {
			
			for (int i = 0; i < result.size(); i++) {
				UserDistanceVO user = result.get(i);
				MarkerOptions userMarkerOption = new MarkerOptions();
				userMarkerOption.position(new LatLng(Double.parseDouble(user.getUserLatitude()), Double.parseDouble(user.getUserLongitude())));
				userMarkerOption.title(user.getUserCname());
				userMarkerOption.draggable(true);
				if (user.getUserHead() != null && !user.getUserHead().equals("")) {
					View markIcon = setMarkIconView(user.getUserHead());
					userMarkerOption.icon(BitmapDescriptorFactory.fromView(markIcon));
				}else{
					String userHead = "http://pic74.nipic.com/file/20150806/20968868_172407221000_2.jpg";
					String imageUrl = "http://img.jzjtwd.com/e4c712d92dfa48a6b89c5e6462a143d7?imageMogr2/thumbnail/!50p/quality/20";  
					View markIcon = setMarkIconView(userHead);
					userMarkerOption.icon(BitmapDescriptorFactory.fromView(markIcon));
				}
				Marker addMarker = aMap.addMarker(userMarkerOption);
				addMarker.showInfoWindow();
				addMarker.setObject(user.getUserId());
			}
			
		}
		marker2 = aMap.addMarker(markerOption);
		marker2.showInfoWindow();

	}

	/**
	 * 监听amap地图加载成功事件回调
	 */
	private AMap.OnMapLoadedListener onMapLoadedListener = new AMap.OnMapLoadedListener() {

		@Override
		public void onMapLoaded() {

			// 设置所有maker显示在当前可视区域地图中
			// latLng - 可视区域框移动目标点屏幕中心位置的经纬度
			// zoom - 可视区域的缩放级别，高德地图支持3-20 级的缩放级别
			aMap.moveCamera((CameraUpdateFactory.newLatLngZoom(latlng, 16)));

		}
	};

	
	private OnMarkerClickListener onMarkerClickListener = new  OnMarkerClickListener() {
		
		@Override
		public boolean onMarkerClick(Marker mark) {
			if (mark.getTitle() != null && !mark.getTitle().equals("")) {
				
				ChatMishowActivity.intoActivity(mActivity,mark.getObject().toString(),mark.getTitle());
			}
			return false;
		}
	};
	/**
	 * 监听自定义infowindow窗口的infoWindow事件监听器
	 */
	private AMap.OnInfoWindowClickListener onInfoWindowClickListener = new AMap.OnInfoWindowClickListener() {

		@Override
		public void onInfoWindowClick(Marker marker) {

		}
	};

	/**
	 * 监听自定义infowindow窗口的infowindow事件回调
	 */
	private AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {

		@Override
		public View getInfoWindow(Marker marker) {

			View infoWindow = mActivity.getLayoutInflater().inflate(R.layout.custom_info_window, null);
			render(marker, infoWindow);
			return infoWindow;
		}

		@Override
		public View getInfoContents(Marker marker) {
			return null;
		}
	};

	/**
	 * 自定义infowinfow窗口
	 */
	@SuppressWarnings("deprecation")
	public void render(Marker marker, View view) {
		String title = marker.getTitle();
		ArrayList<BitmapDescriptor> icons = marker.getIcons();
		TextView titleUi = ((TextView) view.findViewById(R.id.txt_info_title));
		RoundCornerImageView image_user_haed = (RoundCornerImageView)view.findViewById(R.id.image_user_haed);
		image_user_haed.setRectAdius(10);
		
		if (icons != null && icons.size() > 0) {
			for (int i = 0; i < icons.size(); i++) {
				//String imageUrl = "http://img.jzjtwd.com/e4c712d92dfa48a6b89c5e6462a143d7?imageMogr2/thumbnail/!50p/quality/20"; 
				//ImageLoaderProxy.getInstance(mActivity).displayImage(imageUrl, image_user_haed, R.drawable.icon_clinic_loaction_pin);
			}
		}
		if (title != null) {
			titleUi.setText(title);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		// 在activity执行onResume时执行mMapView.onResume ()，实现地图生命周期管理
		map_view.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
		// 在activity执行onPause时执行mMapView.onPause ()，实现地图生命周期管理
		map_view.onPause();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		// 在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
		map_view.onDestroy();
		aMap = null;
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		//在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，实现地图生命周期管理
		map_view.onSaveInstanceState(outState);
	}
	
	/**
	 * 服务端获取附近的人
	 * 
	 */
	private void getDistanceUserFromApi() {

		if (!AndroidUtil.isNetworkAvailable(mActivity)) {
			ToastUtil.show(mActivity,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());//用户ID（存在不查询当前用户）
		
		params.put("userLongitude", mShPreferencesUtil.getLongitude());//经度
		params.put("userLatitude", mShPreferencesUtil.getLatitude());//纬度

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mActivity, params);

		String postUrl = HttpUrlConstant.getPostUrl(mActivity,
				HttpUrlConstant.GET_DISTANCE_USER);
		OnResponseListener<UserDistanceResponse> listener = new OnResponseListener<UserDistanceResponse>(mActivity) {

			@Override
			public void onSuccess(UserDistanceResponse response) {

				Result result = response.getBody().getResult();
				if (result != null) {

					setDisplayData(result.getDataList());
				}
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mActivity, message);
			}

			@Override
			public void onCompleted() {
				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<UserDistanceResponse>(
				Request.Method.POST, postUrl, UserDistanceResponse.class,
				listener, listener).setParams(lastParams));
	}
	
	
	private void setDisplayData(ArrayList<UserDistanceVO> result){
		
		addMarkersToMap(result);// 往地图上添加marker
	}
	
	
	public View setMarkIconView(String imageUrl){
        View view = LayoutInflater.from(mActivity).inflate(R.layout.custom_mark_icon, null);  
        RoundCornerImageView imageView = (RoundCornerImageView) view.findViewById(R.id.image_user_mark);  
        ImageLoaderProxy.getInstance(mActivity).displayImage(imageUrl, imageView, R.drawable.icon_clinic_loaction_pin);
        return view;
	}
	
	/**
	 * 下载网络图片
	 * @param url 
	 * @return
	 */
	public Bitmap setMarkIconBitmap(String url) {
	    Bitmap bitmap = null;
	    View view = View.inflate(mActivity, R.layout.custom_mark_icon, null);
	    RoundCornerImageView imageView = (RoundCornerImageView) view.findViewById(R.id.image_user_haed);
	    ImageLoaderProxy.getInstance(mActivity).displayImage(url, imageView, R.drawable.icon_clinic_loaction_pin);
	    bitmap = convertViewToBitmap(view);
	    return bitmap;
	}
	/**
	 * view转化为图片的方法，网上类似的方法有很多
	 * @param view
	 * @return
	 */
	@SuppressLint("NewApi")
	public static Bitmap convertViewToBitmap(View view) {
	    view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
	    view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
	    view.buildDrawingCache();
	    Bitmap bitmap = view.getDrawingCache();
	    bitmap.setHeight(80);
	    bitmap.setWidth(80);
	    return bitmap;
	}


}
